import TimeUtil from 'js-common-modules/lib/utils/TimeUtil'
import hardConfig from '../constants/hardConfig'

export default class Block {

  constructor () {
    this._generating = false
    this.delegators = hardConfig['coinbaseDelegators']  // 所有代表
    this.nextWorkDelegator = 0
  }

  async startGeneBlockTimer () {
    if (this._generating === false) {
      this._generating = true
      await this._geneBlock()
      TimeUtil.setInterval(async () => {
        await this._geneBlock()
        return !this._generating
      }, 4000)
    }
  }

  stopGeneBlockTimer () {
    this._generating = false
  }

  async _geneBlock () {
    // 检查是否该自己产块
    const workDelegator = blockHelper.delegators[blockHelper.nextWorkDelegator]
    logger.error('产块者：', workDelegator)
    for (let account of accountHelper.accounts) {
      if (account['address'] === workDelegator['address']) {
        // 开始产块 TODO
        logger.info(`该我生产区块了`)

        break
      }
    }
  }

  async getLocalLatestHeight () {
    return sqliteHelper.count({
      from: 'blocks',
    })
  }

  async getBlocks (start ,limit) {
    return sqliteHelper.select({
      select: '*',
      from: 'blocks',
      limit: [start, limit]
    })
  }

}
